import { Tools } from "../../common/Tools";
import { AudioManager1 } from "../../manager/AudioManager1";
import { EventManager } from "../../manager/EventManager";
import { UIManager } from "../../manager/UIManager";
import TouchScale from "../../item/Common/TouchScale";
import LevelBase from "../../LevelBase";
import LvItem from "../../LvItem";
import LvItem_18 from "./LvItem_18";
import { BUNDLE_TYPE_ENUM, EVENT_NAME_ENUM } from "../../base/EnumIndex";
import { TOUCH_MOVE_LEN } from "../../base/GameIndex";
import TouchMoves from "../TouchMoves";

const { ccclass, property } = cc._decorator;

/** 找茬类关卡 */
@ccclass
export default class LevelPre_18 extends LevelBase {
    @property(cc.Node)
    viewBg: cc.Node = null;

    @property(cc.Node)
    maskNode: cc.Node = null;
    @property(cc.Node)
    downContent: cc.Node = null;
    @property(cc.Node)
    itemBg: cc.Node = null;
    @property(cc.Node)
    downItem: cc.Node = null;
    @property(cc.Node)
    tipNode: cc.Node = null;


    /** 已经完成数组 */
    finishItemArr: Array<LvItem_18> = [];
    /** 本关的交互配置 */
    interJson: any = null;
    moneyNum: number = 0;

    start() {
        // cc.macro.ENABLE_MULTI_TOUCH = false;  //是否开起多点触摸
        EventManager.ins.on(EVENT_NAME_ENUM.FINISH_INTER_TWEEN, this.finishTween, this);
    }
    onDestroy(): void {
        super.onDestroy();
        EventManager.ins.off(EVENT_NAME_ENUM.FINISH_INTER_TWEEN, this.finishTween, this);
    }
    init(huaPre: cc.Prefab) {
        for (let i = 0; i < this.interJson.keyNum; i++) {
            let node = cc.instantiate(this.itemBg);
            node.y = 0;
            this.downContent.addChild(node);
        }
        this.huaNode = cc.instantiate(huaPre);
        this.maskNode.addChild(this.huaNode);
        // 适配
        let widthScale = this.maskNode.width / this.huaNode.width;
        let heightScale = this.maskNode.height / this.huaNode.height;
        this.huaNode.scale = Math.min(widthScale, heightScale);

        this.huaNode.getComponent(TouchScale).maskNode = this.maskNode;
        // this.huaNode.getComponent(TouchScale).updateMinScale();

        this.initTouch();
        this.initHuaItem();

    }

    huaNode: cc.Node = null;   //画的节点
    finishTween(finishStr: any, lvItem: LvItem) {
        if (typeof finishStr != "string") {
            if (finishStr.sayInfo) {   //人物说话
                lvItem.node.getComponent(LvItem_18).sayNodeTween(finishStr.sayInfo);
            }
            if (finishStr.str) {   //人物说话
                this.saySubtitleNodeTween(finishStr);
            }
            return;
        }
        if (typeof finishStr != "string") {

            return;
        }
        if (finishStr.includes("setClick_")) {  //设置一个lvItem_17的click
            let str = finishStr.split("setClick_")[1];
            this.setLvItemClick(lvItem.node, str == "true" ? true : false);
        }
        if (finishStr.includes("addMoney_")) {  //刷新金钱数
            let str = finishStr.split("addMoney_")[1];
            if (lvItem.node.getComponent(LvItem_18)) {
                lvItem.node.getComponent(LvItem_18).updateMoeny(parseInt(str))
            }
            this.updateMoney(parseInt(str));
        }
        if (finishStr.includes("finishItem_")) {  //刷新金钱数
            let str = finishStr.split("finishItem_")[1];
            let node = this.getNodeForName(str);
            node.getComponent(LvItem_18).runInterEvent();
        }
        if (finishStr.includes("updateIsWin")) {  //刷新是否胜利
            this.updateIsWin();
        }
        if (finishStr.includes("overGame")) {  //游戏结束 倒计时
            this.overGame();
        }
        if (finishStr.includes("setTouchMove_")) {  //设置touchMoves脚本开关
            let str = finishStr.split("setTouchMove_")[1];
            if (str == "true") {
                lvItem.node.getComponent(TouchMoves).onTouchMove();
            } else {
                lvItem.node.getComponent(TouchMoves).offTouchMove();
            }
        }
        if (finishStr.includes("setIsRunTw_")) {  //
            let str = finishStr.split("setIsRunTw_")[1];
            lvItem.node["isRunTw"] = str == "true" ? true : false
        }


    }
    lastSayAudio: string = null;
    /** 执行说话事件 */
    async saySubtitleNodeTween(sayInfo: any) {
        let tempT = 3;
        if (sayInfo.audio) {
            AudioManager1.stopAudioForName(this.lastSayAudio);
            let audio = await AudioManager1.playAudio(sayInfo.audio.resUrl, sayInfo.audio.value, BUNDLE_TYPE_ENUM.LEVEL);
            this.lastSayAudio = sayInfo.audio.resUrl;
            tempT = cc.audioEngine.getDuration(audio) + 0.2;
        }

        if (sayInfo.armAni) {
            this.runArmAni(sayInfo.armAni, sayInfo.armAni.shuo, sayInfo.armAni.node);
        }

        if (sayInfo.str) {
            this.showTipNodeLab(sayInfo.str, tempT, sayInfo);
        }
        return tempT;
    };
    /** 通过sayInfo执行龙骨动画 */
    runArmAni(armAni: any, aniName: string, sayNode?: cc.Node) {
        if (!armAni) { return; }
        let node = sayNode.parent;
        if (armAni.node) {
            node = this.getNodeForName(armAni.node);
        }
        node.getComponent(LvItem).playArmtureAni(aniName);
    };
    /** 显示提示文字  time 显示时间 */
    showTipNodeLab(str: string, time: number, sayInfo: any) {
        if (!this.tipNode) return;
        if (!AudioManager1.isSubtitle) {
            this.tipNode.active = false;
        };
        cc.Tween.stopAllByTarget(this.tipNode);

        let lab = this.tipNode.getComponentInChildren(cc.Label);
        if (str != "") {
            lab.string = str;
        }
        cc.tween(this.tipNode)
            .to(0.5, { opacity: 255 })
            .delay(time)
            .call(() => {
                if (sayInfo.armAni) {
                    this.runArmAni(sayInfo.armAni, sayInfo.armAni.daiji, sayInfo.armAni.node);
                }
                if (this.interJson["sayUpdateIsWin"]) {
                    this.updateIsWin();
                }
            }).to(0.5, { opacity: 0 }).start();
    };

    touchStartPos: cc.Vec3 = null;
    /** 初始化触摸 */
    initTouch() {
        if (cc.sys.os == cc.sys.OS_WINDOWS) {
            this.huaNode.on(cc.Node.EventType.MOUSE_WHEEL, (touches: cc.Event.EventMouse) => {
                this.huaNode.getComponent(TouchScale).mouseWheelCall(touches);
            }, this);
        }
        this.huaNode.on(cc.Node.EventType.TOUCH_START, (touches: cc.Touch) => {
            this.touchStartPos = cc.v3(touches.getLocation());
        }, this);
        this.huaNode.on(cc.Node.EventType.TOUCH_MOVE, (touchs: cc.Event.EventTouch) => {
            if (!this.touchStartPos || Tools.getDistance(this.touchStartPos, touchs.getLocation()) <= TOUCH_MOVE_LEN) { return; }
            this.huaNode.getComponent(TouchScale).touchMoveCall(touchs);
        }, this);
        this.huaNode.on(cc.Node.EventType.TOUCH_END, (touchs: cc.Event.EventTouch) => {
            this.huaNode.getComponent(TouchScale).touchMoveEnd(touchs);
        }, this);
    };
    /** 根据配置初始化 item */
    async initHuaItem() {
        for (let i = 0; i < this.interJson.itemInfos.length; i++) {
            const info = this.interJson.itemInfos[i];
            let node = this.getChildForName(info.node)
            if (!node) { continue; }
            node.addComponent(LvItem_18).initItem(info, this);
            if (node.getComponent(LvItem)) { continue; }
            node.addComponent(LvItem).initItem(this);
        }

        this.updateMoney(this.interJson.initMoney);
    };

    /** 刷新报价 */
    updateMoney(num: number = 0) {
        this.moneyNum += num;
        this.moneyNum = Math.round((this.moneyNum * 100)) / 100;
        if (this.interJson.moneyTitle) {
            EventManager.ins.emit(EVENT_NAME_ENUM.UPDATE_GOAL, this.moneyNum);
        }
        if (this.interJson.sliderScore) {
            EventManager.ins.emit(EVENT_NAME_ENUM.UPDATE_SLIDER, this.moneyNum / 10);
        }
    }

    keyCorret(lvItem: LvItem_18) {
        this.finishItemArr.push(lvItem);
        if (this.finishItemArr.length >= this.interJson.keyNum) {
            UIManager.ins.enabledClick(false);

        }
        if (this.finishItemArr.length == this.interJson.keyNum - 1) {
            if (this.getInterTwForName("overItemTw")) {
                this.runNodeTween(this.viewBg, this.getInterTwForName("overItemTw").interTween);
            }
        }
        let interTw = this.getInterTwForName("finishItem_" + this.finishItemArr.length);
        if (interTw) {
            this.runNodeTween(this.node, interTw.interTween);
        }

        if (this.interJson.finishInfos) {   //是否完成特殊item
            for (let i = 0; i < this.interJson.finishInfos.length; i++) {
                const info = this.interJson.finishInfos[i];
                if (info.nodes.indexOf(lvItem.config.node) < 0) {
                    continue;
                }
                let isRun = true;
                for (let j = 0; j < info.nodes.length; j++) {
                    if (!this.isFinishItem(info.nodes[j])) {
                        isRun = false;
                        break;
                    }
                }
                if (isRun) {
                    this.runNodeTween(this.viewBg, this.getInterTwForName(info.interTween).interTween);
                }
            }
        }
        if (this.finishItemArr.length > 3) {
            let toX = this.finishItemArr.length < (this.interJson.keyNum - 3) ? -345 + (this.finishItemArr.length - 3) * -100 : this.downContent.parent.width / 2 - this.downContent.width;
            cc.tween(this.downContent).to(0.08, { x: toX }).start();
        }
    };
    /** 完成节点里面是否有该节点 */
    isFinishItem(node: string) {
        for (let i = 0; i < this.finishItemArr.length; i++) {
            if (this.finishItemArr[i].config.node == node) {
                return true;
            }
        }
        return false;
    };
    /** 是否过关 */
    getIsWin() {
        if (this.interJson.winType == "DengYu") {
            if (this.moneyNum == this.interJson.winMoney) { return true; }
            return false;
        }

        if (this.interJson.winType == "XiaoYu") {
            if (this.moneyNum > this.interJson.winMoney) { return false; }
        } else {
            if (this.moneyNum < this.interJson.winMoney) { return false; }
        }
        return true;
    };
    isOver: boolean = false;  //是否游戏结束
    /** 刷新是否胜利 */
    updateIsWin() {
        if (this.finishItemArr.length < this.interJson.keyNum) { return; }
        if (this.isOver) { return; }
        if (this.getIsWin()) {
            this.isOver = true;
            if (this.interJson["isWin"] === false) {
                this.runNodeTween(this.viewBg, this.getInterTwForName("bianshou").interTween);
                return;
            }
            UIManager.ins.enabledClick(false);

            EventManager.ins.emit(EVENT_NAME_ENUM.STOP_TIME);
            this.runNodeTween(this.viewBg, this.getInterTwForName("winGame").interTween);
        } else {
            this.isOver = true;
            UIManager.ins.enabledClick(false);
            this.runNodeTween(this.viewBg, this.getInterTwForName("overGame").interTween);
        }
    };
    /** 游戏结束 */
    overGame() {
        UIManager.ins.enabledClick(false);

        EventManager.ins.emit(EVENT_NAME_ENUM.STOP_TIME);
        this.runNodeTween(this.viewBg, this.getInterTwForName("overGame").interTween);
    };
    /** 设置本关Item的Click */
    setLvItemClick(node: cc.Node, isClick: boolean) {
        if (node.getComponent(LvItem_18)) {
            console.log(node, isClick)
            node.getComponent(LvItem_18).isClick = isClick;
        } else {
            console.log("节点" + node.name + "上没有添加LvItem脚本");
        }
    }
};
